package trycatch;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.junit.jupiter.api.Test;

public class TryCatchStream {
	
	@Test
	public void read() {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream("aaa.txt");
			byte[] content = new byte[fis.available()];
			fis.read(content);
			System.out.println(new String(content));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	@Test      // jdk1.8新增的写法
	public void read2() {
		// 会自动调用fis.close()方法
		try(FileInputStream fis = new FileInputStream("aaa.txt")) {
			byte[] content = new byte[fis.available()];
			fis.read(content);
			System.out.println(new String(content));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
